<template>
  <div class="admin-job-fairs">
    <div class="page-header">
      <h2 class="page-title">招聘会管理</h2>
      <el-button type="primary" @click="handleCreateJobFair">
        <el-icon><Plus /></el-icon>发布招聘会
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" :inline="true">
        <el-form-item label="招聘会名称">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入招聘会名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="举办状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="未开始" value="upcoming" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 招聘会列表 -->
    <el-card class="job-fair-list">
      <el-table :data="jobFairList" style="width: 100%" v-loading="loading">
        <el-table-column label="招聘会信息" min-width="300">
          <template #default="{ row }">
            <div class="job-fair-info">
              <div class="title">{{ row.title }}</div>
              <div class="meta">
                <el-tag size="small" type="info">{{ row.location }}</el-tag>
                <el-tag size="small" type="warning">线下招聘会</el-tag>
                <el-tag size="small" type="success">{{ row.registeredCompanies || 0 }}/{{ row.companyLimit }}家企业</el-tag>
                <el-tag size="small" type="warning">{{ row.positions || 0 }}个职位</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="时间" min-width="200">
          <template #default="{ row }">
            <div>{{ row.startTime }}</div>
            <div style="color: #909399;">至</div>
            <div>{{ row.endTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报名情况" width="200">
          <template #default="{ row }">
            <div class="registration-stats">
              <div class="stat-item">
                <span class="label">企业报名：</span>
                <span class="value">{{ row.registeredCompanies }}</span>
              </div>
              <div class="stat-item">
                <span class="label">求职者报名：</span>
                <span class="value highlight">{{ row.registeredUsers }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetails(row)">查看详情</el-button>
            <el-button link type="primary" @click="editJobFair(row)">编辑</el-button>
            <el-button 
              v-if="row.status === 'upcoming' || row.status === 0"
              link 
              type="danger" 
              @click="cancelJobFairAction(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 招聘会表单对话框 -->
    <el-dialog
      v-model="jobFairDialogVisible"
      :title="jobFairForm.id ? '编辑招聘会' : '发布招聘会'"
      width="800px"
    >
      <el-form :model="jobFairForm" label-width="100px" :rules="jobFairRules">
        <el-form-item label="招聘会名称" prop="title">
          <el-input v-model="jobFairForm.title" placeholder="请输入招聘会名称" />
        </el-form-item>
        <el-form-item label="举办时间" prop="time" required>
          <el-date-picker
            v-model="jobFairForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="举办地点" prop="location">
          <el-input v-model="jobFairForm.location" placeholder="请输入举办地点" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="jobFairForm.address" placeholder="请输入详细地址，便于求职者导航" />
        </el-form-item>
        <el-form-item label="海报图片" prop="poster">
          <el-input v-model="jobFairForm.poster" placeholder="请输入海报图片URL" maxlength="500" show-word-limit>
            <template #append>
              <el-button @click="showPosterExamples">查看示例</el-button>
            </template>
          </el-input>
          <div class="form-tip">请输入完整的网络图片URL地址，建议使用直接的图片链接而非搜索链接，链接长度需小于500字符。建议图片尺寸比例为3:4</div>
        </el-form-item>
        <el-form-item label="招聘行业" prop="industryIds">
          <el-select
            v-model="jobFairForm.industryIds"
            multiple
            placeholder="请选择招聘行业"
            style="width: 100%"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业容量" prop="companyLimit">
          <el-input-number 
            v-model="jobFairForm.companyLimit" 
            :min="1" 
            :max="999"
            placeholder="参展企业数量上限"
          />
        </el-form-item>
        <el-form-item label="求职者容量" prop="userLimit">
          <el-input-number 
            v-model="jobFairForm.userLimit" 
            :min="1" 
            :max="9999"
            placeholder="参会求职者数量上限"
          />
        </el-form-item>
        <el-form-item label="招聘会简介" prop="description">
          <el-input
            v-model="jobFairForm.description"
            type="textarea"
            rows="4"
            placeholder="请输入招聘会简介"
          />
        </el-form-item>
        <el-form-item label="参会须知" prop="notice">
          <el-input
            v-model="jobFairForm.notice"
            type="textarea"
            rows="4"
            placeholder="请输入参会须知"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="jobFairForm.contact"
            type="textarea"
            rows="4"
            placeholder="请输入联系方式"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="jobFairDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitJobFair" :loading="submitLoading">
            {{ jobFairForm.id ? '保存' : '发布' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getJobFairs, createJobFair, updateJobFair, cancelJobFair } from '@/api/jobfair'

// 添加路由实例
const router = useRouter()

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
})

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 行业选项
const industryOptions = [
  { value: 1, label: '互联网/IT' },
  { value: 2, label: '金融/银行/保险' },
  { value: 3, label: '教育/培训' },
  { value: 4, label: '医疗健康' },
  { value: 5, label: '制造业' },
  { value: 6, label: '房地产/建筑' },
  { value: 7, label: '汽车/交通运输' },
  { value: 8, label: '服务业' },
  { value: 9, label: '文化传媒' },
  { value: 10, label: '能源/化工' }
]

// 招聘会列表数据
const jobFairList = ref([])

// 获取招聘会列表
const fetchJobFairList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined,
      status: searchForm.status ? mapStatusToNumber(searchForm.status) : undefined,
      type: 0 // 只获取线下招聘会
    }
    
    const response = await getJobFairs(params)
    
    if (response && response.data) {
      jobFairList.value = response.data.records
      total.value = response.data.total
    } else {
      jobFairList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取招聘会列表失败', error)
    ElMessage.error('获取招聘会列表失败')
    jobFairList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 状态字符串转数字
const mapStatusToNumber = (status) => {
  const map = {
    'upcoming': 0,
    'ongoing': 1,
    'ended': 2,
    'canceled': 3
  }
  return map[status]
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    0: 'primary',
    'upcoming': 'primary',
    1: 'success',
    'ongoing': 'success',
    2: 'info',
    'ended': 'info',
    3: 'danger',
    'canceled': 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '未开始',
    'upcoming': '未开始',
    1: '进行中',
    'ongoing': '进行中',
    2: '已结束',
    'ended': '已结束',
    3: '已取消',
    'canceled': '已取消'
  }
  return map[status] || status
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchJobFairList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchJobFairList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchJobFairList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchJobFairList()
}

// 招聘会表单相关
const jobFairDialogVisible = ref(false)
const jobFairForm = reactive({
  id: '',
  title: '',
  time: [],
  location: '',
  companyLimit: 100,
  userLimit: 1000,
  description: '',
  notice: '',
  contact: '',
  type: 0,
  address: '',
  industryIds: [],
  poster: ''
})

// 表单校验规则
const jobFairRules = {
  title: [{ required: true, message: '请输入招聘会名称', trigger: 'blur' }],
  time: [{ required: true, message: '请选择举办时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入举办地点', trigger: 'blur' }],
  companyLimit: [{ required: true, message: '请输入企业容量', trigger: 'blur' }],
  userLimit: [{ required: true, message: '请输入求职者容量', trigger: 'blur' }],
  description: [{ required: true, message: '请输入招聘会简介', trigger: 'blur' }],
  notice: [{ required: true, message: '请输入参会须知', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  industryIds: [{ required: true, message: '请选择招聘行业', trigger: 'change' }],
  poster: [
    { required: true, message: '请输入海报图片URL', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 验证是否是有效的URL
        try {
          new URL(value)
          // 检查是否是图片URL（简单检查）
          const imgExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']
          const isImageUrl = imgExtensions.some(ext => 
            value.toLowerCase().includes(ext) || 
            value.toLowerCase().includes('image') ||
            value.toLowerCase().includes('img')
          )
          if (!isImageUrl) {
            callback(new Error('链接不是常见的图片URL格式'))
          } else if (value.length > 500) {
            callback(new Error('URL过长，请使用更短的直接图片链接'))
          } else {
            callback()
          }
        } catch (err) {
          callback(new Error('请输入有效的URL地址'))
        }
      }, 
      trigger: 'blur'
    }
  ]
}

// 添加海报URL示例
const posterExamples = [
  'https://example.com/images/job-fair.jpg',
  'https://cdn.example.com/posters/fair-2025.png'
]

// 显示示例
const showPosterExamples = () => {
  ElMessage({
    message: '示例图片链接格式：\n' + posterExamples.join('\n'),
    type: 'info',
    duration: 5000
  })
}

// 禁用的日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 创建新招聘会
const handleCreateJobFair = () => {
  Object.keys(jobFairForm).forEach(key => {
    if (key === 'companyLimit') {
      jobFairForm[key] = 100
    } else if (key === 'userLimit') {
      jobFairForm[key] = 1000
    } else if (key === 'type') {
      jobFairForm[key] = 0  // 始终设置为线下招聘会
    } else if (key === 'industryIds') {
      jobFairForm[key] = []
    } else if (key === 'poster') {
      jobFairForm[key] = ''
    } else {
      jobFairForm[key] = ''
    }
  })
  jobFairDialogVisible.value = true
}

// 编辑招聘会
const editJobFair = (row) => {
  Object.keys(jobFairForm).forEach(key => {
    if (key === 'time') {
      jobFairForm.time = [row.startTime, row.endTime]
    } else if (key === 'industryIds' && row.industryIds) {
      jobFairForm.industryIds = [...row.industryIds]
    } else if (key === 'type') {
      jobFairForm[key] = 0  // 无论原类型如何，始终设置为线下招聘会
    } else {
      jobFairForm[key] = row[key]
    }
  })
  jobFairDialogVisible.value = true
}

// 提交招聘会
const submitJobFair = async () => {
  submitLoading.value = true
  try {
    // 构建数据
    const data = {
      id: jobFairForm.id,
      title: jobFairForm.title,
      location: jobFairForm.location,
      startTime: jobFairForm.time[0],
      endTime: jobFairForm.time[1],
      companyLimit: jobFairForm.companyLimit,
      userLimit: jobFairForm.userLimit,
      description: jobFairForm.description,
      notice: jobFairForm.notice,
      contact: jobFairForm.contact,
      type: 0,  // 始终设置为线下招聘会
      address: jobFairForm.address,
      industryIds: jobFairForm.industryIds,
      poster: jobFairForm.poster
    }
    
    let response
    if (jobFairForm.id) {
      // 更新
      response = await updateJobFair(jobFairForm.id, data)
    } else {
      // 创建
      response = await createJobFair(data)
    }
    
    if (response && response.data) {
      ElMessage.success(jobFairForm.id ? '招聘会已更新' : '招聘会已发布')
      jobFairDialogVisible.value = false
      fetchJobFairList()
    }
  } catch (error) {
    console.error('提交招聘会失败', error)
    ElMessage.error(error.message || '提交招聘会失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消招聘会
const cancelJobFairAction = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该招聘会吗？取消后将无法恢复。', '提示', {
      type: 'warning'
    })
    
    const response = await cancelJobFair(row.id)
    
    if (response) {
      ElMessage.success('招聘会已取消')
      fetchJobFairList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消招聘会失败', error)
      ElMessage.error(error.message || '取消招聘会失败')
    }
  }
}

// 查看招聘会详情
const viewDetails = (row) => {
  router.push(`/admin/job-fairs/${row.id}/detail`)
}

// 初始化
fetchJobFairList()
</script>

<style lang="scss" scoped>
.admin-job-fairs {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .job-fair-list {
    flex: 1;
    display: flex;
    flex-direction: column;

    .el-card__body {
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .el-table {
      flex: 1;
    }

    .job-fair-info {
      .title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 8px;
        color: #303133;
      }

      .meta {
        display: flex;
        gap: 8px;
      }
    }

    .registration-stats {
      .stat-item {
        margin-bottom: 4px;
        font-size: 14px;

        .label {
          color: #909399;
        }

        .value {
          font-weight: 600;
          margin-left: 4px;

          &.highlight {
            color: #409EFF;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .form-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
  }
}
</style> 